<?php
declare(strict_types=1);

namespace app\api\controller;

use app\common\library\Http;
use think\annotation\route\Get;
use think\annotation\route\Post;
use think\annotation\route\Group;
use think\facade\Cache;
use app\common\service\upload\PublicUploadService;
use app\common\model\User;
use app\common\model\Area;

#[Group("common")]
class Common extends Api{
    protected $noNeedLogin = ['*'];
    /**
     * 上传文件
     * @param File $file 文件流
     */
    #[Post('upload')]
    public function upload()
    {
        $file = $this->request->file('file');
        try{
            $savename=PublicUploadService::newInstance([
                'config'=>config('site.upload'),
                'user_id'=>$this->auth->id,
                'file'=>$file
            ])->save();
        }catch (\Exception $e){
            $this->error(__('上传文件出错'),[
                'file'=>$e->getFile(),
                'line'=>$e->getLine(),
                'msg'=>$e->getMessage()
            ]);
        }
        $this->success('',$savename);
    }

    #[Post('bdmobile')]
    public function bdmobile()
    {
        $data=$this->request->post();
        if(!$data['code']){
            $this->error('请输入手机验证码');
        }
        $code=Cache::get('sms_code_'.$data['mobile']);
        if($code!=$data['code']){
            $this->error('验证码不正确');
        }
        $user=User::find($this->auth->id);
        $user->mobile=$data['mobile'];
        $user->save();
        $this->success('绑定成功');
    }

    #[Post('cardinfo')]
    public function cardinfo()
    {
        $img=$this->request->post('url');
        $config=[
            'appid'=>site_config("goodsdelivery.miniapp_id"),
            'appsecret'=>site_config("goodsdelivery.miniapp_secret")
        ];
        $menu = new \WeChat\User($config);
        $token=$menu->getAccessToken();
        $response=Http::post("https://api.weixin.qq.com/cv/ocr/comm?access_token={$token}&img_url={$img}");
        $result=$response->content;
        $txt='';
        $address='';
        if(!isset($result['items'])){
            $this->success('',$txt);
        }
        foreach ($result['items'] as $value){
            preg_match("/\w{18}/",$value['text'],$match);
            if($match && count($match)==1 && strlen($match[0])==18){
                $txt=$match[0];
            }
            if(
                strpos($value['text'],'贵州省')!==false ||
                strpos($value['text'],'云南省')!==false ||
                strpos($value['text'],'陕西省')!==false ||
                strpos($value['text'],'四川省')!==false ||
                strpos($value['text'],'重庆市')!==false ||
                strpos($value['text'],'湖南省')!==false ||
                strpos($value['text'],'广西省')!==false ||
                strpos($value['text'],'广东省')!==false
            ){
                $address=$value['text'];
            }
        }
        $this->success('',[
            'code'=>$txt,
            'address'=>$address
        ]);
    }

    #[Post('sendmsg')]
    public function sendmsg()
    {
        $mobile = $this->request->post('mobile');
        $template = 'SMS_461170083';
        if (!$mobile) {
            $this->error('手机号不能为空');
        }
        $code=rand(1000,9999);
        Cache::set('sms_code_'.$mobile,$code,60*10);
        $param = ['code'=>$code];
		if(!class_exists('\\app\\common\\library\\Alisms')){
            $this->error("请安装阿里云短信插件");
        }
        $alisms = new \app\common\library\Alisms();
        $ret = $alisms->mobile($mobile)
            ->template($template)
            ->param($param)
            ->send();
        if ($ret) {
            $this->success("发送成功");
        } else {
            $this->error("发送失败！失败原因：" . $alisms->getError());
        }
    }

    #[Get('area')]
    public function area($pid)
    {
        $area=Area::where('pid',$pid)->field('id,name')->select();
        $this->success('',$area);
    }

    #[Get('address')]
    public function address($area_id)
    {
        $area=Area::where('id',$area_id)->find();
        $this->success('',$area);
    }

    #[Get('wxuser')]
    public function wxuser()
    {
        $keywords=$this->request->get('keywords');
        $where=function($query) use ($keywords){
            if($keywords){
                $query->where('nickname|mobile','like',"%{$keywords}%");
            }
        };
        $list=User::where($where)->limit(10)->order('id desc')->field('id,nickname,avatar,mobile')->select();
        $this->success('',$list);
    }
}